<template>
    <div style="width:100%;height:100%;overflow:hidden">
        <div style="display:flex">
            <div style="flex:1">
                <weui-search-bar :list="[]" placeholder="粘贴商品标题或链接，查询优惠" @on-search="on_search_bar_0_search"
                                 @on-input="on_search_bar_0_input">
                </weui-search-bar>
            </div>
            <div>
                <weui-button type="primary" :is_plain="true" :font_size="17" @on-click="on_search_bar_0_search">
                    <i style="font-family:iconfont;font-style:normal;">&#xe606;</i>
                </weui-button>
            </div>
        </div>
        <!--a href="/jiaocheng.html"><img src="../img/jiaocheng.jpg" style="width:100%"></a-->
        <div style="display:flex">
            <div style="flex:1;text-align:center" @click="dialog_0_is_show = true">
                {{shops.indexOf('taobao') != -1 ? '淘宝' : ''}}
                {{shops.indexOf('jd') != -1 ? '京东' : ''}}
                {{shops.length == 0 ? '请选择商城' : ''}}
            </div>
            <div style="flex:1;text-align:center" @click="dialog_1_is_show = true">
                {{order_by}}
            </div>
        </div>
        <div v-show="is_loading" style="text-align:center">
            <weui-icon type="loading">
            </weui-icon>
        </div>
        <weui-panel title="" :list="panel_0_list" style="overflow-y:auto" class="hidden-sm-and-up"
                    :style="{maxHeight: 'calc(100% - ' + (is_loading ? 85 : 65) + 'px)'}"
                    v-if="is_mobile"
                    @on-click="on_panel_0_click">
        </weui-panel>
        <div style="overflow-y:auto;padding:0 5px;"
             :style="{maxHeight: 'calc(100% - ' + (is_loading ? 85 : 65) + 'px)'}"
             v-else>
            <el-row :gutter="10" class="hidden-xs-only" v-for="i in Math.ceil(panel_0_list.length / 4)" :key="i">
                <el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6"
                        v-for="(item, j) in panel_0_list.slice(i * 4 - 4, i * 4)"
                        :key="item.link">
                    <el-card :body-style="{ padding: '0px' }" @click="on_panel_0_click(i * 4 - 4 + j)">
                        <img v-lazy="item.img" style="width:100%">
                        <div style="padding: 14px;">
                            <div>{{item.title}}</div>
                            <div v-html="item.desc" style="font-size:14px;color:#333333"></div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <weui-dialog title="选择商城" :list="dialog_0_list" :is_show="dialog_0_is_show" @on-click="dialog_0_on_click">
            <weui-input title="" more_label="" agreement_name="" :tips="null" :list="input_0_list">
            </weui-input>
        </weui-dialog>
        <weui-dialog title="选择排序方式" :list="dialog_0_list" :is_show="dialog_1_is_show" @on-click="dialog_1_on_click">
            <weui-input title="" more_label="" agreement_name="" :tips="null" :list="input_1_list">
            </weui-input>
        </weui-dialog>
        <weui-dialog title="淘口令" :list="dialog_0_list" :is_show="dialog_2_is_show" @on-click="dialog_2_on_click">
            长按复制本条本条信息{{dialog_2_content}}，然后打开手机淘宝
        </weui-dialog>
        <weui-toast :is_show="loading_is_show" type="loading" :content="loading_content">
        </weui-toast>
        <weui-dialog :is_show="code_dialog_is_show" title="请输入验证码" :list="['提交']"
                     @on-click="on_code_dialog_click">
            <weui-input :list="code_dialog_input_list" title="" :show_more="false" :tips="null"
                        agreement_name="" more_label=""></weui-input>
        </weui-dialog>
    </div>
</template>

<script>
    import WeuiSearchBar from '../vue2componentSet/src/components/WeuiSearchBar'
    import WeuiPanel from '../vue2componentSet/src/components/WeuiPanel'
    import WeuiButton from '../vue2componentSet/src/components/WeuiButton'
    import WeuiDialog from '../vue2componentSet/src/components/WeuiDialog'
    import WeuiInput from '../vue2componentSet/src/components/WeuiInput'
    import WeuiIcon from '../components/WeuiIcon'
    import WeuiToast from '../components/WeuiToast'
    import global from '../lib/global'
    import browserDetect from '../lib/browserDetect'
    import axios from 'axios'

    export default {
        components: {
            WeuiSearchBar,
            WeuiPanel,
            WeuiButton,
            WeuiDialog,
            WeuiInput,
            WeuiIcon,
            WeuiToast
        },
        data() {
            return {
                itemList: {
                    taobao: [],
                    jd: []
                },
                search_text: '',
                last_search_text: '',
                input_0_list: [{
                    type: 'checkbox',
                    value: [],
                    list: [{
                        label: '淘宝',
                        value: 'taobao'
                    }, {
                        label: '京东',
                        value: 'jd'
                    }]
                }],
                dialog_0_list: ['取消', '确定'],
                dialog_0_is_show: false,
                shops: [],
                need_get_code: 0,
                code_dialog_is_show: false,
                code: '',
                codeRequestId: 0,
                is_loading: 0,
                search_id: 0,
                order_by: '默认排序',
                dialog_1_is_show: false,
                input_1_list: [{
                    type: 'radio',
                    value: '默认排序',
                    list: [{
                        value: '默认排序',
                        label: '默认排序'
                    }, {
                        value: '按官方标价排序',
                        label: '按官方标价排序'
                    }, {
                        value: '按折后参考价排序',
                        label: '按折后参考价排序'
                    }]
                }],
                is_mobile: browserDetect().mobile,
                loading_is_show: false,
                loading_content: '正在计算返现金额',
                dialog_2_is_show: false,
                dialog_2_content: ''
            }
        },
        mounted() {
            this.$store.commit('set_title', '旅悠首页')

            this.input_0_list[0].value.push('taobao')
            //this.input_0_list[0].value.push('jd')
            this.shops.push('taobao')
            //this.shops.push('jd')
        },
        methods: {
            openAdvLink(link) {
                if (!this.$store.state.customer) {
                    this.$store.commit('login_dialog', {
                        is_show: true,
                        resolve: () => {
                            this.openAdvLink(link)
                        }
                    })
                    return
                }
                this.need_get_code++
                this.need_get_code == 1 && this.get_code()
                this.loading_is_show = true
                axios.post(global.server + 'getAdvLink.do', {
                    link: link
                }).then(result => {
                    const obj = result.data
                    if (obj.result == 0) {
                        this.$store.commit('customer_login', null)
                        this.$store.commit('login_dialog', {
                            is_show: true,
                            resolve: () => {
                                this.openAdvLink(link)
                            }
                        })
                    } else if (obj.result == -1) {
                        if (obj.msg == '该商品不能返利') {
                            this.$store.commit('dialog', {
                                is_show: true,
                                title: '错误',
                                content: obj.msg,
                                list: ['关闭', '继续前往'],
                                'on-click': index => {
                                    if (index == 0) {
                                        this.$store.commit('dialog', {
                                            is_show: false
                                        })
                                    } else if (index == 1) {
                                        //location.href = link
                                        const node = document.getElementById('open-url')
                                        node.href = link
                                        node.click()
                                    }
                                }
                            })
                        } else {
                            this.$store.commit('dialog', {
                                is_show: true,
                                title: '错误',
                                content: obj.msg,
                                list: ['确定'],
                                'on-click': index => {
                                    this.$store.commit('dialog', {
                                        is_show: false
                                    })
                                }
                            })
                        }
                    } else {
                        new Promise(resolve => {
                            if (obj.rate && obj.price) {
                                this.$store.commit('toast', {
                                    content: '本次购物返现金额预计为' + Math.round(obj.price * obj.rate) / 100 + '元(' + obj.rate + '%)',
                                    type: 'success'
                                })
                                setTimeout(() => {
                                    resolve()
                                }, 2000)
                                return
                            }
                            resolve()
                        }).then(result => {
                            if (obj.advLink.indexOf('taobao') != -1 || obj.advLink.indexOf('tmall') != -1) {
                                if (browserDetect().wechat) {
                                    if (obj.tpwd) {
                                        this.dialog_2_content = obj.tpwd
                                        this.dialog_2_is_show = true
                                    } else {
                                        this.$store.commit('toast', {
                                            type: 'warn',
                                            content: '请用系统浏览器打开'
                                        })
                                    }
                                    return
                                }
                            }
                            if (browserDetect().Safari || browserDetect().FireFox) {
                                location.href = obj.advLink
                            } else {
                                const node = document.getElementById('open-url')
                                node.href = obj.advLink
                                node.click()
                            }
                        })
                    }
                    this.need_get_code--
                    this.loading_is_show = false
                }, result => {
                    console.log(result)
                    this.need_get_code--
                    this.loading_is_show = false
                })
            },
            search(shop) {
                shop = shop || 'taobao'
                if (this.itemList[shop].length > 0) {
                    return
                }
                if (!this.search_text.trim()) {
                    return
                }
                this.is_loading++
                var url = global.server
                var data = {}
                if (shop == 'taobao') {
                    url += 'getTaobaoItem.do'
                    data.q = this.search_text.trim()
                } else {
                    url += 'getJdItem.do'
                    data.keyword = this.search_text.trim()
                }
                this.need_get_code++
                this.need_get_code == 1 && this.get_code()
                var search_id = this.search_id
                axios.post(url, data).then(result => {
                    if (search_id != this.search_id) {
                        return
                    }
                    const obj = result.data
                    if (obj.result == -1) {
                        this.itemList[shop].push({
                            title: '抱歉，没有找到相关商品'
                        })
                    } else {
                        if (obj.list.length == 0) {
                            this.itemList[shop].push({
                                title: '抱歉，没有找到相关商品'
                            })
                        } else {
                            obj.list.forEach(item => {
                                this.itemList[shop].push(item)
                            })
                        }
                    }
                    this.is_loading--
                    this.need_get_code--
                }, result => {
                    if (search_id != this.search_id) {
                        return
                    }
                    console.log(result)
                    this.itemList[shop].push({
                        title: '抱歉，没有找到相关商品'
                    })
                    this.is_loading--
                    this.need_get_code--
                })
            },
            on_panel_0_click(index) {
                if (!this.panel_0_list[index].rawLink) {
                    return
                }
                this.openAdvLink(this.panel_0_list[index].rawLink)
            },
            on_search_bar_0_input(value) {
                this.search_text = value
            },
            get_code() {
                if (this.need_get_code <= 0) {
                    this.code_dialog_is_show = false
                    return
                }
                axios.post(global.server + 'getFanliCode.do', {}).then(result => {
                    const obj = result.data
                    if (obj.code) {
                        if (obj.codeRequestId != this.codeRequestId) {
                            if (this.need_get_code > 0) {
                                this.code_dialog_is_show = true
                                this.code = 'data:image/png;base64,' + obj.code
                                this.codeRequestId = obj.codeRequestId
                            }
                        }
                    } else {
                        this.code_dialog_is_show = false
                    }
                    setTimeout(() => {
                        this.get_code()
                    }, 1000)
                }, result => {
                    console.log(result)
                    this.code_dialog_is_show = false
                })
            },
            dialog_0_on_click(index) {
                if (index == 1) {
                    var shops = []
                    this.input_0_list[0].value.forEach(item => {
                        shops.push(item)
                    })
                    this.shops = shops
                    this.on_search_bar_0_search()
                }
                this.dialog_0_is_show = false
            },
            on_search_bar_0_search() {
                if (this.last_search_text != this.search_text) {
                    this.last_search_text = this.search_text
                    for (var shop in this.itemList) {
                        this.itemList[shop].splice(0, this.itemList[shop].length)
                    }
                }
                var match = /https?:\/\/\S+/.exec(this.search_text)
                if (match) {
                    this.openAdvLink(match[0])
                    return
                }
                match = /￥.+￥/.exec(this.search_text) || /€.+€/.exec(this.search_text) || /\$.+\$/.exec(this.search_text)
                if (match) {
                    this.openAdvLink(match[0])
                    return
                }
                this.search_id++
                this.shops.forEach(shop => {
                    this.search(shop)
                })
            },
            on_code_dialog_click(index) {
                if (index == 0) {
                    axios.post(global.server + 'submitFanliCode.do', {
                        codeRequestId: this.codeRequestId,
                        codeText: this.code_dialog_input_list[0].value
                    }).then(result => {
                    }, result => {
                    })
                }
            },
            dialog_1_on_click(index) {
                if (index == 1) {
                    this.order_by = this.input_1_list[0].value
                }
                this.dialog_1_is_show = false
            },
            dialog_2_on_click(index) {
                this.dialog_2_is_show = false
            }
        },
        computed: {
            panel_0_list() {
                var list = []
                var i = 0
                while (true) {
                    var hasMore = false
                    this.shops.forEach(shop => {
                        if (!this.itemList[shop] || this.itemList[shop].length <= i || !this.itemList[shop][i].link) {
                            return
                        }
                        hasMore = true
                        var item = this.itemList[shop][i]
                        var img = item.img
                        if (browserDetect().Safari && img.endsWith('_.webp')) {
                            img = img.substring(0, img.length - 6)
                        }
                        var desc = ''
                        item.price && (desc += '价格: ￥' + item.price)
                        item.rate && (desc += '<br>返还: ' + item.rate + '%')
                        var infos = []
                        item.sale && infos.push('销量: ' + item.sale)
                        item.shopName && infos.push('店名: ' + item.shopName)
                        list.push({
                            img: img,
                            title: item.title,
                            desc: desc,
                            infos: infos,
                            rawLink: item.link,
                            price: item.price,
                            rate: item.rate
                        })
                    })
                    i++
                    if (!hasMore) {
                        break
                    }
                }
                if (list.length == 0) {
                    var isSearching = false
                    this.shops.forEach(shop => {
                        isSearching = isSearching || this.itemList[shop].length == 0
                    })
                    if (!isSearching) {
                        list.push({
                            title: '抱歉，没有找到相关商品'
                        })
                    }
                    return list
                }
                if (this.order_by == '按官方标价排序') {
                    for (var i = 0; i < list.length; i++) {
                        for (var j = i + 1; j < list.length; j++) {
                            if (parseFloat(list[i].price) > parseFloat(list[j].price)) {
                                var item = list[i]
                                list[i] = list[j]
                                list[j] = item
                            }
                        }
                    }
                } else if (this.order_by == '按折后参考价排序') {
                    for (var i = 0; i < list.length; i++) {
                        for (var j = i + 1; j < list.length; j++) {
                            if (parseFloat(list[i].price) * (100 - list[i].rate) > parseFloat(list[j].price) * (100 - list[j].rate)) {
                                var item = list[i]
                                list[i] = list[j]
                                list[j] = item
                            }
                        }
                    }
                }
                return list
            },
            code_dialog_input_list() {
                return [{
                    value: '',
                    img: this.code
                }]
            }
        },
        watch: {
//      code_dialog_is_show(value) {
//        if (value) {
//          this.$store.commit('loading', {
//            is_show: false
//          })
//        } else if (this.need_get_code > 0) {
//          this.commit('loading', {
//            is_show: true,
//            content: '加载中'
//          })
//        }
//      }
        }
    }
</script>
